/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pocketsweet.chat.ui.activity;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NotificationCompat;
import android.view.View;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.Type;
import com.easemob.util.EasyUtils;
import com.pocketsweet.MLCache;
import com.pocketsweet.R;
import com.pocketsweet.MLApplication;
import com.pocketsweet.chatui.utils.CommonUtils;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.Splash;
import com.pocketsweet.ui.TempMain;

public class BaseActivity extends FragmentActivity {
    private static final int notifiId = 11;
    protected static final int NEW_FRIEND_APPLY = 2015;
    protected static final int NEW_LIKE = 2016;
    protected NotificationManager notificationManager;
    private MLApplication mlApplication;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        if(arg0 != null){
            Intent intent = new Intent(getApplicationContext(),
                    Splash.class);
            PendingIntent restartIntent = PendingIntent.getActivity(
                    getApplicationContext(), 0, intent,
                    Intent.FLAG_ACTIVITY_NEW_TASK);
            AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis(),
                    restartIntent);
            MLApplication.getInstance().finishActivity();
        }



        mlApplication = MLApplication.getInstance();
        mlApplication.addActivity(this);
        Intent intent1 = new Intent();
        intent1.setClassName("com.pocketsweet.ui", "TempMain");
        if (MLApplication.getInstance().isLogin == true || intent1.resolveActivity(getPackageManager()) == null) {//登录以后要检查currentuser是否为空

            if (UserService.getCurrentUser() == null) {
                Intent intent = new Intent(getApplicationContext(),
                        Splash.class);
                PendingIntent restartIntent = PendingIntent.getActivity(
                        getApplicationContext(), 0, intent,
                        Intent.FLAG_ACTIVITY_NEW_TASK);
                AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                mgr.set(AlarmManager.RTC, System.currentTimeMillis(),
                        restartIntent);
                mlApplication.finishActivity();
            }
            if (UserService.getCurrentUser() == null) {
                System.exit(0);
                Intent intent = new Intent(this, Splash.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                // Intent k = getBaseContext().getPackageManager()
                // .getLaunchIntentForPackage(getBaseContext().getPackageName());
                // k.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                // startActivity(k);
            }
        }
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // onresume时，取消notification显示
        Intent intent1 = new Intent();
        intent1.setClassName("com.pocketsweet.ui", "TempMain");
        if (MLApplication.getInstance().isLogin == true || intent1.resolveActivity(getPackageManager()) == null) {//登录以后要检查currentuser是否为空

            if (UserService.getCurrentUser() == null) {
                Intent intent = new Intent(getApplicationContext(),
                        Splash.class);
                PendingIntent restartIntent = PendingIntent.getActivity(
                        getApplicationContext(), 0, intent,
                        Intent.FLAG_ACTIVITY_NEW_TASK);
                AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                mgr.set(AlarmManager.RTC, System.currentTimeMillis(),
                        restartIntent);
                mlApplication.finishActivity();
            }
            if (UserService.getCurrentUser() == null) {
                System.exit(0);
                Intent intent = new Intent(this, Splash.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                // Intent k = getBaseContext().getPackageManager()
                // .getLaunchIntentForPackage(getBaseContext().getPackageName());
                // k.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                // startActivity(k);
            }
        }
        EMChatManager.getInstance().activityResumed();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        mlApplication.removeActivity(this);
        super.onDestroy();
        // destroyActivityLocked(true);
    }

    /**
     * 当应用在前台时，如果当前消息不是属于当前会话，在状态栏提示一下 如果不需要，注释掉即可
     *
     * @param message
     */
    public void notifyNewMessage(EMMessage message) {
        // 如果是设置了不提醒只显示数目的群组(这个是app里保存这个数据的，demo里不做判断)
        // 以及设置了setShowNotificationInbackgroup:false(设为false后，后台时sdk也发送广播)
        if (!EasyUtils.isAppRunningForeground(this)) {
            return;
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(getApplicationInfo().icon)
                .setWhen(System.currentTimeMillis()).setAutoCancel(true);

        String ticker = CommonUtils.getMessageDigest(message, this);
        String st = getResources().getString(R.string.expression);
        if (message.getType() == Type.TXT)
            ticker = ticker.replaceAll("\\[.{2,3}\\]", st);
        // 设置状态栏提示
        String name = MLCache.getNickById(message.getFrom());
        mBuilder.setTicker(name + ": " + ticker);

        // 必须设置pendingintent，否则在2.3的机器上会有bug
        MLApplication.getInstance().isLogin = true;
        Intent intent = new Intent(this, Main.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, notifiId,
                intent, PendingIntent.FLAG_ONE_SHOT);
        mBuilder.setContentIntent(pendingIntent);

        Notification notification = mBuilder.build();
        notificationManager.notify(notifiId, notification);
        notificationManager.cancel(notifiId);
    }

    @SuppressWarnings("deprecation")
    protected void notifyThoughMessage(EMMessage message, Class<?> cls,
                                       int notificationId, Bundle bundle) {
        NotificationManager nm = (NotificationManager) MLApplication
                .getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        Notification n = new Notification(getApplicationInfo().icon,
                message.getStringAttribute("msg", ""),
                System.currentTimeMillis());
        n.flags = Notification.FLAG_AUTO_CANCEL;// 点击后消失
        Intent i = new Intent(MLApplication.getContext(), cls);
        if (bundle != null) {
            i.putExtras(bundle);
        }
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);// 设置启动模式为恢复

        PendingIntent contentIntent = PendingIntent.getActivity(
                MLApplication.getContext(), notificationId, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        n.setLatestEventInfo(MLApplication.getContext(), "通知",
                message.getStringAttribute("msg", ""), contentIntent);
        nm.notify(notificationId, n);
    }

    /**
     * 返回
     *
     * @param view
     */
    public void back(View view) {
        finish();
    }

}
